import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.Field

//global variable
@Field String GITURL = "https://git.augmentum.com.cn"
@Field String PRIVATE_TOKEN="1qfBxwCzmLRknsuFZQXs"

def sendGetRequest(String apiUrl)
{
    def connection = new URL("${GITURL}/${apiUrl}").openConnection() as HttpURLConnection
    //必须是GET方法
    connection.setRequestMethod("GET")
    connection.setRequestProperty('User-Agent', 'groovy-'.concat(GroovySystem.getVersion()))
    connection.setRequestProperty('Accept', 'application/json')
    //必须设置PRIVATE-TOKEN，不然返回404状态
    connection.setRequestProperty('PRIVATE-TOKEN', "${PRIVATE_TOKEN}")
    def response = connection.inputStream.text
//    println(response.toString())
    return response
}

def jsonParsing(String result)
{
    //json处理
    def slurper = new JsonSlurper()
    def jsonText = slurper.parseText(JsonOutput.prettyPrint(result.toString()))
    return jsonText
}

def call()
{
    gitlabSourceRepoHomepage= "https://git.augmentum.com.cn/smartconstruction/platform-frontend"
    //gitlabSourceRepoHomepage= "https://git.augmentum.com.cn/AugCI/jenkins-pipeline/spring-boots-docker"

    String[] keys;
    keys = gitlabSourceRepoHomepage.split('/')[3..-1] //截取 group+project
    //println keys  //[AugCI, jenkins-pipeline, spring-boots-docker] OR [smartconstruction, platform-frontend]
    groupName=keys[0]

    if (keys.length <3)
    {
        projectName=keys[1]
    }
    else
    {
        projectName=keys[1]+"%2F"+keys[2]
    }

    def emailList=[]
    // 1. 根据project name得到project id
    def responseProject=sendGetRequest("/api/v4/projects/${groupName}%2F${projectName}")
    def jsonProject=jsonParsing(responseProject)
    def projectID=jsonProject.id

    // 2. 根据project id得到 project member detail
    def responseMembers=sendGetRequest("/api/v4/projects/${projectID}/members")
    def jsonMembers=jsonParsing(responseMembers)
    def membersID=jsonMembers.id as String[]

    // 3. 根据 project member ID 得到对应email
    for(String memberID in membersID) {
        def responseMember=sendGetRequest("/api/v4/users/${memberID}")
        def jsonMember=jsonParsing(responseMember)
        emailList.add(jsonMember.email)
    }

    // 4. 根据group name 得到group member detail
    def responseGroupMembers=sendGetRequest("/api/v4/groups/${groupName}/members")
    def jsonGroupMembers=jsonParsing(responseGroupMembers)
    def groupMembersID=jsonGroupMembers.id as String[]

    // 5. 根据 group member ID 得到对应 email
    for(String memberID in groupMembersID) {
        def responseMember=sendGetRequest("/api/v4/users/${memberID}")
        def jsonMember=jsonParsing(responseMember)
        emailList.add(jsonMember.email)
    }

    println(emailList)

}

// call()






